package me.zhangyifeng.blog.web.controller.admin;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import me.zhangyifeng.blog.model.domain.Activity;
import me.zhangyifeng.blog.model.domain.User;
import me.zhangyifeng.blog.model.dto.JsonResult;
import me.zhangyifeng.blog.model.dto.MaydayConst;
import me.zhangyifeng.blog.service.ActivityService;

/**
 * 后台活动管理控制器
 * 
 * @author zhangyifeng
 */
@Controller
@RequestMapping("/admin/activities")
public class ActivityAdminController extends BaseController {
    
    @Autowired
    private ActivityService activityService;
    
    /**
     * 格式化日期
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
    
    /**
     * 活动管理页面
     */
    @GetMapping
    public String activities(Model model) {
        List<Activity> activities = activityService.findAllActivities();
        model.addAttribute("activities", activities);
        
        return "admin/admin_activities";
    }
    
    /**
     * 添加活动页面
     */
    @GetMapping("/new")
    public String newActivity() {
        return "admin/admin_activity_edit";
    }
    
    /**
     * 编辑活动页面
     */
    @GetMapping("/edit/{activityId}")
    public String editActivity(@PathVariable("activityId") Integer activityId, Model model) {
        Activity activity = activityService.findActivityById(activityId);
        if (activity == null) {
            return "redirect:/admin/activities";
        }
        
        model.addAttribute("activity", activity);
        
        return "admin/admin_activity_edit";
    }
    
    /**
     * 保存活动
     */
    @PostMapping("/save")
    @ResponseBody
    public JsonResult saveActivity(Activity activity) {
        if (activity.getActivityId() == null) {
            // 创建新活动
            return activityService.createActivity(activity);
        } else {
            // 更新活动
            return activityService.updateActivity(activity);
        }
    }
    
    /**
     * 删除活动
     */
    @PostMapping("/remove")
    @ResponseBody
    public JsonResult removeActivity(@RequestParam("id") Integer activityId) {
        return activityService.deleteActivity(activityId);
    }
    
    /**
     * 查看活动参与者
     */
    @GetMapping("/participants/{activityId}")
    public String participants(@PathVariable("activityId") Integer activityId, Model model) {
        Activity activity = activityService.findActivityById(activityId);
        if (activity == null) {
            return "redirect:/admin/activities";
        }
        
        model.addAttribute("activity", activity);
        model.addAttribute("participants", activityService.findParticipantsByActivityId(activityId));
        
        return "admin/admin_activity_participants";
    }
    
    /**
     * 上传活动封面图
     */
    @PostMapping("/upload/cover")
    @ResponseBody
    public JsonResult uploadCover(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return new JsonResult(false, "请选择要上传的图片");
        }
        
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        
        // 生成文件名
        Random random = new Random();
        fileName = "activity_" + System.currentTimeMillis() + "_" + random.nextInt(1000) + suffixName;
        
        // 上传文件路径
        String uploadPath = request.getSession().getServletContext().getRealPath("/") + "upload/activity/";
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        
        try {
            // 保存文件
            file.transferTo(new File(uploadPath + fileName));
            
            // 返回访问路径
            String filePath = "/upload/activity/" + fileName;
            return new JsonResult(true, "上传成功", filePath);
        } catch (Exception e) {
            return new JsonResult(false, "上传失败：" + e.getMessage());
        }
    }
}
